<template>
  <div>
    <div class="search">
      <input v-model="keyword"
        type="text"
        class="search-input"
        placeholder="输入城市名或拼音">
    </div>
    <div class="search-content"
      ref="search"
      v-show="keyword">
      <ul>
        <li class="search-item border-bottom"
          v-for="item of matchCities"
          :key="item.id"
          @click=handleCityClick(item.name)>
          {{ item.name }}
        </li>
        <li class="search-item border-bottom"
          v-show="hasNoData">
          没有找到匹配数据
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      matchCities: [],
      timer: null
    }
  },
  computed: {
    hasNoData () {
      return !this.matchCities.length
    },
    cityList () {
      const cityList = []
      for (const key in this.cities) {
        if (this.cities.hasOwnProperty(key)) {
          const element = this.cities[key]
          cityList.push(element)
        }
      }
      return cityList
    }
  },
  watch: {
    keyword (newValue) {
      if (!newValue) {
        this.matchCities = []
        return
      }
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.findMatch(newValue)
      }, 100)
    }
  },
  methods: {
    findMatch (keyword) {
      const matchs = []
      keyword = keyword.trim()
      this.cityList.forEach(branch => {
        branch.forEach(city => {
          if (city.name.includes(keyword) || city.spell.includes(keyword)) {
            matchs.push(city)
          }
        })
      })
      this.matchCities = matchs
    },
    handleCityClick (city) {
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  mounted () {
    this.$nextTick(() => {
      this.scroll = new BScroll(this.$refs.search)
    })
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/variables.styl'
  .search
    height .72rem
    background $bgColor
    padding 0 .1rem
    .search-input
      box-sizing border-box
      width 100%
      height .62rem
      line-height .62rem
      padding 0 .1rem
      border-radius .06rem
      text-align center
      color #666
  .search-content
    overflow hidden
    position absolute
    z-index 1
    top 1.58rem
    left 0
    right 0
    bottom 0
    background #eee
    .search-item
      line-height .62rem
      padding-left .2rem
      color #666
      background #fff
</style>
